<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

global $JFXRegistry, $formErrors;
if(!is_array($JFXRegistry)) $JFXRegistry = array();
if(!is_array($formErrors)) $formErrors = array();

class JFX{


     /*
     * called by hooks in various places to enable other modules to interact with each other ( search in files for "event(" )
     * Accepts: method name, array of parameters
     * returns: array with two indexes: content and values, being any output from the call,
     * 	and whatever values are returned by the module
     * NB: modules are called in alphabetical order
     *
     * @param string $methodName
     * @param array $params
     * @return array $returnParams containing resulting parameters and output
     */
    function hook($methodName, &$params){

        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');

        if($CONFIG->useCache){
            if($DB->countRows($CONFIG->dbprefix.'hooks', '1=1')==0){
                // rebuild hook cache
                $MM = JFX::registry('JFX_Module_Manager');
                $MM->rebuildHookCache();
            }
            $safeHook = $DB->escape($methodName);
            $hooks = (array) $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}hooks WHERE hook LIKE '{$safeHook}%' ORDER BY sorting ASC");
            foreach($hooks as $k=>$v){
                if($v['is_module']) $obj = JFX::registry('JFX_Module_'.ucfirst(strtolower($v['keyname'])));
                else $obj = JFX::registry('JFX_Theme_'.ucfirst(strtolower($v['keyname'])));
                $obj->hook($methodName, $params);
            }
            return;
        }

        $THEME = JFX::registry('JFX_Theme');

        $THEME->hook($methodName, $params);

        $installedModules = JFX_Module::getInstalledModules();

        foreach ($installedModules as $module){
            $moduleKey = $module['keyname'];
            $module = $module['object'];
            if(is_object($module) && is_callable(array($module, 'hook'))){
                $module->hook($methodName, $params);
            }
        }




    }


    public static function fetchSmarty($template){
        $SMARTY = JFX::registry('Smarty');
        $SMARTY->_compile_source('JFX::smartyFetch', $template, $_compiled);
        ob_start();
        $SMARTY->_eval('?>' . $_compiled);
        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }

    public static function getUrlParamsAsArray($url=''){
        $LINK = JFX::registry('JFX_Link');
        return $LINK->getUrlParamsAsArray($url);
    }

    public function interpretUrlParams($url=''){
        $LINK = JFX::registry('JFX_Link');
        return $LINK->interpretUrlParams($url);
    }

    public static function getUrlById($id){
        $LINK = JFX::registry('JFX_Link');
        return $LINK->getUrlById($id);
    }


    public function getUrlByAlias($alias){
        $LINK = JFX::registry('JFX_Link');
        return $LINK->getUrlBySlug($id);
    }

    public function getUrlBySlug($slug){
        return JFX::getUrlByAlias($slug);
    }

    public function addParamsToUrl($url, $params){
        $LINK = JFX::registry('JFX_Link');
        return $LINK->addParamsToUrl($url, $params);
    }

    public static function getPageContent($pageid, $workspaceid=''){
        $LINK = JFX::registry('JFX_Link');
        $LANG = JFX::registry('lang');
        $VIEW = JFX::registry('JFX_View');
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $USER = JFX::registry('JFX_User');

        if($workspaceid==''){
            if((int) $USER->workspace > 0)
                $workspaceid = $USER->workspace;
            else
                $workspaceid = 1;
        }

        $pData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}pages WHERE id = '{$pageid}'");

        JFX::hook('JFX_Core.CmsRenderPre', $pData);

        $blocks = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}blocks WHERE parent_id = 'jfxpage-{$pageid}' AND workspace_id = '{$workspaceid}' ORDER BY exec_order ASC");
        $sortedBlocks = array();

        foreach($blocks as $k=>$v){
            $block = new JFX_Block;
            $block->loadById($v['id'], $workspaceid, false, true);
            $block->prepare();
            JFX::register('JFX_Block_'.$v['id'], $block);
        }

        $content = '';
        $sortedBlocks = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}blocks WHERE parent_id = 'jfxpage-{$pageid}' AND page_parent = 1 AND workspace_id = '{$workspaceid}' ORDER BY sorting ASC");
        $block = new JFX_Block;
        foreach($sortedBlocks as $k=>$v){
            $block->loadById($v['id'], $workspaceid, true, false);
            $content .= $block->render();
        }

        $JFXMemDebug[] = array('bytes'=>memory_get_usage(), 'file'=>__FILE__, 'line'=>__LINE__, 'time' => getmicrotime(), 'desc' => 'After rendering all page blocks');

        $content = $LINK->parseLinks($content);

        JFX::hook('JFX_Core.postCmsRender', $pData);

        $JFXMemDebug[] = array('bytes'=>memory_get_usage(), 'file'=>__FILE__, 'line'=>__LINE__, 'time' => getmicrotime(), 'desc' => 'After converting urls');

        return $content;
    }


    public static function throw404(){
        global $pageLoadStartTime;
        $LINK = JFX::registry('JFX_Link');
        $LINK->throw404();
    }












    /**
     * Redirects the user to the last significant page viewed, set by Antz::setLastPage()
     *
     */
    public static function goLastPage()
    {
        $url = JFX::getLastPage();
        $CONFIG = JFX::registry('config');
        while($url == THIS_PAGE_URL && THIS_PAGE_URL != $CONFIG->baseUrl) $url = JFX::getLastPage();
        JFX::redirect($url);
    }





    /**
     * Set the current page or custom url as the last significant page in user's history
     *
     * @param string url
     */
    public static function setLastPage($url='')
    {
        $url = ($url == '') ? THIS_PAGE_URL : $url;
        // add to the stack, only if the top of the stack is not already set to the same value
        if(count($_SESSION['JFXLastPage'])==0)
            $_SESSION['JFXLastPage'][] = $url;
        elseif($_SESSION['JFXLastPage'][count($_SESSION['JFXLastPage'])-1] != $url)
            $_SESSION['JFXLastPage'][] = $url;
    }


    /**
     * Get the url of the last significant page viewed, set by Antz::setLastPage()
     *
     * @param bool $del
     * @return string url
     */
    public static function getLastPage($del=true){
        $CONFIG = JFX::registry('config');
        if(!isset($_SESSION['JFXLastPage'])) $_SESSION['JFXLastPage'] = array();
        if( isset($_SESSION['JFXLastPage'][count($_SESSION['JFXLastPage'])-1]) && $_SESSION['JFXLastPage'][count($_SESSION['JFXLastPage'])-1]!=''){
            $lastPage = $_SESSION['JFXLastPage'][count($_SESSION['JFXLastPage'])-1];
            if($del) unset($_SESSION['JFXLastPage'][count($_SESSION['JFXLastPage'])-1]);
        }else{
            if($user->isAdmin())
                $lastPage = $CONFIG->adminUrl;
            else
                $lastPage = $CONFIG->baseUrl;
        };
        return $lastPage;
    }







    public static function checkAdminPermsRedirect($moduleKey, $label){
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        if(!$USER->checkAdminPermission($moduleKey, $label)){
            JFX::addError('Insufficient permissions');
            JFX::redirect($CONFIG->adminUrl);
        }
    }

    public static function getParentIdsAsArray($pageid, &$array){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $parentid = $DB->oneValue($CONFIG->dbprefix.'pages', 'parent_id', "id = '{$pageid}'");
        while($parentid != 0){
            $array[] = $parentid;
            $parentid = $DB->oneValue($CONFIG->dbprefix.'pages', 'parent_id', "id = '{$parentid}'");
        }
        $array[] = 0;
    }

    public static function getPageTree($pageid, $workspaceid, $recursive = true){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $pageid = $DB->escape($pageid);
        $workspaceid = (int) $workspaceid;
        $pages = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}pages WHERE parent_id = '{$pageid}' AND workspace_id = '{$workspaceid}' ORDER BY sorting ASC");
        if(!is_array($pages)) $pages = array();
        if($recursive){
            foreach($pages as $k=>$v){
                $pages[$k]['subpages'] = JFX::getPageTree($v['id'], $workspaceid, $recursive);
            }
        }else{
            foreach($pages as $k=>$v){
                $pages[$k]['subpages'] = array();
            }
        }
        //var_dump($pages);
        return $pages;
    }

    public static function arrayToObject($array = array()) {
        if (!empty($array)) {
            $data = false;
            foreach ($array as $akey => $aval) {
                $data -> {$akey} = $aval;
            }
            return $data;
        }
        return false;
    }


    function objectToArray($object){
        if(is_array($object) || is_object($object)){
            $array = array();
            foreach($object as $key => $value){
                $array[$key] = JFX::objectToArray($value);
            }
            return $array;
        }
        return $object;
    }

    public static function register($key, $object){
        global $JFXRegistry;
        $JFXRegistry[$key] = $object;
    }

    public function &registry($key){
        global $JFXRegistry;
        if(!array_key_exists($key, $JFXRegistry)){
            if(class_exists($key, true)){
                $object = new $key;
                JFX::register($key, $object);
                return $object;
            }
        }else{
            return $JFXRegistry[$key];
        }
        $obj = null;
        return $obj;
    }

        /**
     * Display all objects in the registry
     *
     */
    public static function printRegistry(){
        global $JFXRegistry;
        foreach($JFXRegistry as $keyname=>$obj){
            echo $keyname.' : '.get_class($obj).'<br />';
        }
    }


    public static function redirect($url){
        $eParams = array('url' => $url);
        JFX::hook('JFX_Core.redirect', $eParams);
        $url = $eParams['url'];
        header('location: '.$url);
        die('<script type="text/javascript">window.location="'.$url.'"</script>
<a href="'.$url.'">continue</a>');
    }

    public static function getDb($keyname){
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        if(is_object($DB)) return $DB;
        $DB = new JFX_Db($CONFIG->dbhost, $CONFIG->dbuser, $CONFIG->dbpassword, $CONFIG->dbname);
        JFX::register('db', $DB);
        return $DB;
    }


    public static function addFormError($key, $msg='')
    {
        $user = JFX::registry('JFX_User');
        global $formErrors;
        $formErrors[$key] = true;
        if($msg=='')return;
        $formErrors[$key.'_msg'] = $msg;
    }

    public static function isFormError($key)
    {
        global $formErrors;
        $error = false;
        if(array_key_exists($key, $formErrors) && $formErrors[$key]==true) return true;
        else return false;
    }

    public static function getFormError($key)
    {
        global $formErrors;
        if(array_key_exists($key.'_msg', $formErrors)) return $formErrors[$key.'_msg'];
        else return false;
    }

    public static function addSuccess($successMsg)
    {
      	$USER = JFX::registry('JFX_User');
        if(!isset($USER->successLog)) $USER->successLog = array();
        $USER->successLog[] = $successMsg;
    }

    public static function addError($errorMsg)
    { // BEGIN function addError
      	$USER = JFX::registry('JFX_User');
        if(!isset($USER->errorLog)) $USER->errorLog = array();
        $USER->errorLog[] = $errorMsg;
    } // END function addError

    public static function getError($delete=true)
    {
        $user = JFX::registry('JFX_User');
        $THEME = JFX::registry('JFX_Theme');
        $log = (isset($user->errorLog) && count($user->errorLog)>0)
            ? $THEME->implodeErrors($user->errorLog)
            : ''
            ;
        if($delete) unset($user->errorLog);
        return $log;
    }

    public static function getSuccess($delete=true)
    {
        $user = JFX::registry('JFX_User');
        $THEME = JFX::registry('JFX_Theme');
        $log = (isset($user->successLog) && count($user->successLog)>0)
            ? $THEME->implodeSuccesses($user->successLog)
            : ''
            ;
        if($delete) unset($user->successLog);
        return $log;
    }

    /**
     * Returns a form object from supplied form fields array
     *
     * Distictively more convenient than JFX::makeForm() since it creates the form from supplied
     * element descriptions in one block and one fieldset
     *
     * @param array $formFields
     * @param string $legend
     * @param string $intelliFormKey
     * @return object JFX_Form
     */
    public static function makeRapidForm($formFields, $legend, $intelliFormKey='default'){
      $blocks = JFX::prepareRapidForm($formFields, $legend);
        return JFX::makeForm($blocks, $intelliFormKey);
    }



    /**
     * Wrap raw form fields array in compliant format for use with JFX::makeForm
     *
     * @param array $formFields
     * @param string $legend
     * @return array blocks
     */
    public static function prepareRapidForm($formFields, $legend){
        $blocks = array(
            0 => array(
                'type' => 'full',
                'fieldsets' => array(
                    0 => array(
                        'legend' => $legend,
                        'side' => 'left',
                        'fields' => $formFields
                    )
                )
            )
        );
        return $blocks;
    }









/**
 * Create a form field object from given description
 *
 * @param array $field
 * @return object ${"Antz_Form_Component_".$field['type']}
 */
public static function makeFormComponent($field){

	switch($field['type']){
		case 'text':
		case 'textarea':
		case 'raw':
		case 'submit':
		case 'file':
		case 'password':
		case 'hidden':
		case 'button':

			$input = new JFX_Form_Components_Input($field['type'], $field['name'], $field['label'], $field['value']);
			if(isset($field['extra']) && is_array($field['extra'])){
				foreach($field['extra'] as $key3 => $extra){
					$command = '$input->'.$extra['command'].'('.implode(',', $extra['params']).');';
					eval($command);
				};
			};
			if(isset($field['aftertext'])) $input->addAftertext($field['aftertext']);
			if(isset($field['id'])) $input->setId($field['id']);
			if(isset($field['class'])) $input->addClass($field['class']);
			if(isset($field['setWrap']) && !$field['setWrap']) $input->setWrap(false);
			if(isset($field['showLabel']) && !$field['showLabel']) $input->showLabel(false);
			$input->addAfterText(JFX::getFormError($field['name']));
			if(isset($field['required']) && $field['required']) $input->required(true);
			return $input;
		break;
		case 'select':
			$select = new JFX_Form_Components_Select($field['name'], $field['label'], $field['value']);
			foreach($field['options'] as $optKey=>$optVal){
				$select->add($optVal, $optKey);
			};
			if(isset($field['extra']) && is_array($field['extra'])){
				foreach($field['extra'] as $key3 => $extra){
					$command = '$select->'.$extra['command'].'('.implode(', ', $extra['params']).');';
					eval($command);
				};
			};
			if(isset($field['multiple']) && $field['multiple']) $select->setMultiple(true);
			if(isset($field['size'])) $select->setSize($field['size']);
			if(isset($field['aftertext'])) $select->addAftertext($field['aftertext']);
			if(isset($field['id'])) $select->setId($field['id']);
			if(isset($field['class'])) $select->addClass($field['class']);
			if(isset($field['setWrap']) && !$field['setWrap']) $select->setWrap(false);
			if(isset($field['showLabel']) && !$field['showLabel']) $select->showLabel(false);
			$select->addAfterText(JFX::getFormError($field['name']));
			if(isset($field['required']) && $field['required']) $select->required(true);
			return $select;
		break;
		case 'radiogroup':
			$rad = new JFX_Form_Components_RadioGroup($field['name'], $field['value']);
			foreach($field['options'] as $optKey=>$optVal){
				$rad->add($optKey, $optVal);
			};
			if(isset($field['extra']) && is_array($field['extra'])){
				foreach($field['extra'] as $key3 => $extra){
					$command = '$rad->'.$extra['command'].'('.implode(',', $extra['params']).');';
					eval($command);
				};
			};
			if(isset($field['aftertext'])) $rad->addAftertext($field['aftertext']);
			if(isset($field['id'])) $rad->setId($field['id']);
			if(isset($field['class'])) $rad->addClass($field['class']);
			if(isset($field['setWrap']) && !$field['setWrap']) $rad->setWrap(false);
			if(isset($field['showLabel']) && !$field['showLabel']) $rad->showLabel(false);
			$rad->addAfterText(JFX::getFormError($field['name']));
			if(isset($field['required']) && $field['required']) $rad->required(true);
			return $rad;
		break;
		case 'checkbox':
			$chk = new JFX_Form_Components_CheckboxGroup;
			$chk->add($field['name'], $field['label'], $field['value'], $field['checked']);
			if(isset($field['aftertext'])) $chk->addAftertext($field['aftertext']);
			if(isset($field['id'])) $chk->setId($field['id']);
			if(isset($field['class'])) $chk->addClass($field['class']);
			if(isset($field['setWrap']) && !$field['setWrap']) $chk->setWrap(false);
			if(isset($field['showLabel']) && !$field['showLabel']) $chk->showLabel(false);
			$chk->addAfterText(JFX::getFormError($field['name']));
			if(isset($field['required']) && $field['required']) $chk->required(true);
			return $chk;
		break;
		case 'tinymce':
		    if(!isset($field['id'])){
			// cannot make tinymce type without an id
			$txt = new JFX_Form_Components_LongTag('h1', 'tinymce requires id set');
			return $txt;
		    }else{
			$mces = explode(',', $_SESSION['tiny_live_textareas']);
			if(!in_array($field['id'], $mces)) $mces[] = $field['id'];
			$_SESSION['tiny_live_textareas'] = implode(',', $mces);
			$txt = new JFX_Form_Components_Input('textarea', $field['name'], $field['label'], $field['value']);
			if(isset($field['extra']) && is_array($field['extra'])){
        		  foreach($field['extra'] as $key3 => $extra){
        			$command = '$input->'.$extra['command'].'('.implode(',', $extra['params']).');';
        			eval($command);
        		  };
        		};
        		if(isset($field['aftertext'])) $txt->addAftertext($field['aftertext']);
        		if(isset($field['id'])) $txt->setId($field['id']);
        		if(isset($field['class'])) $txt->addClass($field['class']);
        		if(!$wrap) $txt->setWrap(false);
        		if(!$label) $txt->showLabel(false);
        		if(isset($field['required']) && $field['required']) $txt->required(true);
		    };
		break;
		case 'longtag':
		    $tag = new JFX_Form_Components_LongTag($field['tag'], $field['content']);
		    if(isset($field['aftertext'])) $tag->addAftertext($field['aftertext']);
		    if(isset($field['id'])) $tag->setId($field['id']);
		    if(isset($field['class'])) $tag->addClass($field['class']);
		    if(!$wrap) $tag->setWrap(false);
		    if(!$label) $tag->showLabel(false);
		    if(isset($field['required']) && $field['required']) $tag->required(true);
		break;
		case 'shorttag':
		    $tag = new JFX_Form_Components_ShortTag($field['tag'], $field['content']);
		    if(isset($field['aftertext'])) $tag->addAftertext($field['aftertext']);
		    if(isset($field['id'])) $tag->setId($field['id']);
		    if(isset($field['class'])) $tag->addClass($field['class']);
		    if(!$wrap) $tag->setWrap(false);
		    if(!$label) $tag->showLabel(false);
		    if(isset($field['required']) && $field['required']) $tag->required(true);
		break;
	};
}


/**
 * Add CMS Made Simple pages (content) to a drop menu object
 *
 * @param object $sel
 * @param int $parentId
 * @param int $depth
 */
function addPagesToDropMenu(&$sel, $parentId, $workspaceid='', $depth=0){
    $DB = JFX::registry('db');
    $USER = JFX::registry('user');
    $LANG = JFX::registry('lang');
    if($workspaceid == '') $workspaceid = $USER->workspace;
    $pages = JFX::getPageTree($parentId, $workspaceid);
    foreach($pages as $k=>$v){
        $sel->add(str_repeat(' - ', $depth).$LANG->getContent('core', 'page_title', $v['id']), $v['id']);
        if(count($v['subpages'])>0){
            JFX::addPagesToDropMenu($sel, $v['id'], $workspaceid, $depth+1);
        }
    }
}







    /**
     * Makes a form object from supplied array
     *
     * Array must be formatted accordingly: blocks contain fieldsets, fieldsets contain form fields
     *
     * @param array $blocks
     * @param string $intelliFormKey
     * @param bool $wrap
     * @param bool $label
     * @return object JFX_Form
     */
    public static function makeForm($blocks, $intelliFormKey, $wrap=true, $label=true){
        $VIEW = JFX::registry('JFX_View');
        $form = new JFX_Form($intelliFormKey);
        $foundCode = false;
        foreach($blocks as $k=>$block){
            $b = $form->add($block['type']);
            foreach($block['fieldsets'] as $key=>$fieldset){
                $fs = $b->add($fieldset['legend'], $fieldset['side']);
                if(!is_array($fieldset['fields'])) continue;
                foreach($fieldset['fields'] as $key2 => $field){
                    if(count($field)==0) continue;
                    if(!isset($field['type'])) $field['type'] = 'text';
                    switch($field['type']){
                        case 'text':
                        case 'textarea':
                        case 'raw':
                        case 'submit':
                        case 'file':
                        case 'password':
                        case 'hidden':
                        case 'button':
                            if(!array_key_exists('name', $field)) $field['name'] = $field['type'];
                            $input = $fs->addInput($field['type'], $field['name'], $field['label'], $field['value']);
                            if(isset($field['extra']) && is_array($field['extra'])){
                                foreach($field['extra'] as $key3 => $extra){
                                    $command = '$input->'.$extra['command'].'('.implode(',', $extra['params']).');';
                                    eval($command);
                                };
                            };
                            if(isset($field['aftertext'])) $input->addAftertext($field['aftertext']);
                            if(isset($field['id'])) $input->setId($field['id']);
                            if(isset($field['class'])) $input->addClass($field['class']);
                            if(isset($field['disabled'])) $input->disabled($field['disabled']);
                            if(!$wrap) $input->setWrap(false);
                            if(!$label) $input->showLabel(false);
                            if(isset($field['required']) && $field['required']) $input->required(true);
                        break;
                        case 'select':
                            $select = $fs->addSelect($field['name'], $field['label'], $field['value']);
                            foreach($field['options'] as $optKey=>$optVal){
                                if(isset($optVal['options']) && is_array($optVal['options'])){
                                    // doing an optgroup
                                    $optGroup = $select->addOptGroup($optVal['title']);
                                    foreach($optVal['options'] as $optKey=>$optVal){
                                        $optGroup->add($optVal, $optKey);
                                    };
                                }else{
                                    $select->add($optVal, $optKey);
                                };
                            };
                            if(isset($field['extra']) && is_array($field['extra'])){
                                foreach($field['extra'] as $key3 => $extra){
                                    $command = '$select->'.$extra['command'].'('.implode(', ', $extra['params']).');';
                                    eval($command);
                                };
                            };
                            if(isset($field['multiple']) && $field['multiple']) $select->setMultiple(true);
                            if(isset($field['size'])) $select->setSize($field['size']);
                            if(isset($field['aftertext'])) $select->addAftertext($field['aftertext']);
                            if(isset($field['id'])) $select->setId($field['id']);
                            if(isset($field['class'])) $select->addClass($field['class']);
                            if(isset($field['disabled'])) $select->disabled($field['disabled']);
                            if(!$wrap) $select->setWrap(false);
                            if(!$label) $select->showLabel(false);
                            if(isset($field['required']) && $field['required']) $select->required(true);
                        break;
                        case 'radiogroup':
                            $rad = $fs->addRadioGroup($field['name'], $field['label'], $field['value']);

                            if(isset($field['extra']) && is_array($field['extra'])){
                                foreach($field['extra'] as $key3 => $extra){
                                    $command = '$rad->'.$extra['command'].'('.implode(',', $extra['params']).');';
                                    eval($command);
                                };
                            };
                            if(isset($field['aftertext'])) $rad->addAftertext($field['aftertext']);
                            if(isset($field['id'])) $rad->setId($field['id']);
                            if(isset($field['class'])) $rad->addClass($field['class']);
                            if(isset($field['disabled'])) $rad->disabled($field['disabled']);
                            if(isset($field['setWrap']) && !$field['setWrap']) $rad->setWrap(false);
                            if(isset($field['showLabel']) && !$field['showLabel']) $rad->showLabel(false);
                            $rad->addAfterText(JFX::getFormError($field['name']));
                            if(isset($field['required']) && $field['required']) $rad->required(true);
                            foreach($field['options'] as $optKey=>$optVal){
                                $rad->add($optKey, $optVal);
                            }
                        break;
                        case 'checkbox':
                            $chk = $fs->addCheckboxGroup($field['name']);
                            if(isset($field['aftertext'])) $chk->addAftertext($field['aftertext']);
                            if(isset($field['id'])) $chk->setId($field['id']);
                            if(isset($field['class'])) $chk->addClass($field['class']);
                            if(isset($field['disabled'])) $chk->disabled($field['disabled']);
                            if(!$wrap) $chk->setWrap(false);
                            if(!$label) $chk->showLabel(false);
                            if(!array_key_exists('checked', $field)) $field['checked'] = false;
                            $chk->add($field['name'], $field['label'], $field['value'], $field['checked']);
                            $chk->addAfterText(JFX::getFormError($field['name']));
                        break;
                        case 'code':
                            if(!isset($field['id']) || preg_replace('/[^a-zA-Z0-9]/', '', $field['id'])!=$field['id']){
                                // cannot make codepress type without an id
                                $txt = $fs->addLongTag('h1', 'CodePress field requires ID to be set and it must be alphanumeric');
                            }else{
                                $txt = $fs->addInput('textarea', $field['name'], $field['label'], $field['value']);
                                $txt->addClass('codepress');
                                if(isset($field['extra']) && is_array($field['extra'])){
                                    foreach($field['extra'] as $key3 => $extra){
                                        $command = '$input->'.$extra['command'].'('.implode(',', $extra['params']).');';
                                        eval($command);
                                    };
                                };
                                if(isset($field['aftertext'])) $txt->addAftertext($field['aftertext']);
                                if(isset($field['id'])) $txt->setId($field['id']);
                                if(isset($field['class'])) $txt->addClass($field['class']);
                            if(isset($field['disabled'])) $txt->disabled($field['disabled']);

                                if(!$wrap) $txt->setWrap(false);
                                if(!$label) $txt->showLabel(false);
                                if(isset($field['required']) && $field['required']) $txt->required(true);
                                $VIEW->addJs('
                                $(document).ready(function(){
                                    $("input[type=submit]").click(function(){
                                        '.$field['id'].'.textarea.disabled = true;
                                        '.$field['id'].'.toggleEditor();
                                    });
                                });
                                ');

                            }
                        break;
                        case 'be_tinymce':
                           if(!isset($field['id'])){
                                   // cannot make tinymce type without an id
                                $txt = $fs->addLongTag('h1', 'TinyMCE field requires ID to be set');
                            }else{
                                $txt = $fs->addInput('textarea', $field['name'], $field['label'], $field['value']);
                                if(isset($field['extra']) && is_array($field['extra'])){
                                    foreach($field['extra'] as $key3 => $extra){
                                        $command = '$input->'.$extra['command'].'('.implode(',', $extra['params']).');';
                                        eval($command);
                                    };
                                };
                                if(isset($field['aftertext'])) $txt->addAftertext($field['aftertext']);
                                if(isset($field['id'])) $txt->setId($field['id']);
                                if(isset($field['class'])) $txt->addClass($field['class']);
                            if(isset($field['disabled'])) $txt->disabled($field['disabled']);
                                $txt->addClass('tinymce');
                                if(!$wrap) $txt->setWrap(false);
                                if(!$label) $txt->showLabel(false);
                                if(isset($field['required']) && $field['required']) $txt->required(true);
                            };
                        break;
                        case 'longtag':
                            $tag = $fs->addLongTag($field['tag'], $field['content']);
                            if(isset($field['aftertext'])) $tag->addAftertext($field['aftertext']);
                            if(isset($field['id'])) $tag->setId($field['id']);
                            if(isset($field['class'])) $tag->addClass($field['class']);
                            if(isset($field['disabled'])) $tag->disabled($field['disabled']);
                            if(!$wrap) $tag->setWrap(false);
                            if(!$label) $tag->showLabel(false);
                            if(isset($field['required']) && $field['required']) $tag->required(true);
                        break;
                        case 'shorttag':
                            $tag = $fs->addShortTag($field['tag'], $field['content']);
                            if(isset($field['aftertext'])) $tag->addAftertext($field['aftertext']);
                            if(isset($field['id'])) $tag->setId($field['id']);
                            if(isset($field['class'])) $tag->addClass($field['class']);
                            if(isset($field['disabled'])) $tag->disabled($field['disabled']);
                            if(!$wrap) $tag->setWrap(false);
                            if(!$label) $tag->showLabel(false);
                            if(isset($field['required']) && $field['required']) $tag->required(true);
                        break;

                    }
                }
            }
        }

        unset($blocks);
        return $form;
    }




}